<!--
 * Copyright (c) 2013-Now http://jeesite.com All rights reserved.
 * No deletion without permission, or be held responsible to law.
 * @author YDZ
-->
<template>
  <BasicDrawer
    v-bind="$attrs"
    :showFooter="true"
    :okAuth="'pu:order:poOrder:edit'"
    :okText="'提交'"
    @register="registerDrawer"
    @ok="handleSubmit('4')"
    width="90%"
  >
    <!-- :showOkBtn="allowEdit" -->
    <template #title>
      <Icon :icon="getTitle.icon" class="m-1 pr-1" />
      <span> {{ getTitle.value }} </span>
    </template>
    <BasicForm @register="registerForm">
      <template #poOrderCList>
        <a-button
          class="mb-2 mr-2"
          @click="handlePoOrderCAdd"
          v-auth="'pu:order:poOrder:edit'"
          v-show="allowEdit"
        >
          <Icon icon="i-ant-design:plus-circle-outlined" /> {{ t('新增行') }}
        </a-button>
        <a-button
          class="mb-2 mr-2"
          @click="handleFormSys"
          v-auth="'pu:order:poOrder:edit'"
          v-show="allowEdit"
        >
          <Icon icon="ant-design:plus-circle-outlined" /> {{ '扫码新增' }}
        </a-button>
        <a-button
          type="error"
          class="mb-2 mr-2"
          @click="handleCloseRow"
          v-auth="'pu:order:poOrder:edit'"
          v-show="record.djStatus === GlobalSettingEnum.DjStatusEnum.YSH"
        >
          <Icon icon="ant-design:close-circle-outlined" /> {{ t('行关闭') }}
        </a-button>
        <a-button
          type="success"
          class="mb-2"
          @click="handleOpenRow"
          v-auth="'pu:order:poOrder:edit'"
          v-show="record.djStatus === GlobalSettingEnum.DjStatusEnum.YSH"
        >
          <Icon icon="ant-design:check-circle-outlined" /> {{ t('行打开') }}
        </a-button>
        <BasicTable
          @register="registerPoOrderCTable"
          @row-click="handlePoOrderCRowClick"
          @edit-change="rowChange"
        />
      </template>
    </BasicForm>
    <!-- 图纸列表选择 -->
    <ListSelect
      selectType="orderPicSelect"
      :selectList="selectListRef"
      :checkbox="true"
      :queryParams="queryParams"
      @select="handleOrderPicSelect"
      ref="orderPicSelectRef"
      v-show="false"
    />
    <template #centerFooter>
      <a-button
        type="default"
        @click="handleSubmit('9')"
        v-auth="'pu:order:poOrder:edit'"
        v-show="allowEdit"
      >
        <Icon icon="ant-design:save-outlined" /> {{ t('暂存') }}
      </a-button>
    </template>
    <InputForm @register="registerSysDrawer" @success="handleSuccess" />
  </BasicDrawer>
</template>
<script lang="ts" setup name="ViewsPuOrderPoOrderForm">
  import { ref, unref, computed } from 'vue';
  import { useI18n } from '/@/hooks/web/useI18n';
  import { useMessage } from '/@/hooks/web/useMessage';
  import { router } from '/@/router';
  import { Icon } from '/@/components/Icon';
  import { BasicForm, FormSchema, useForm } from '/@/components/Form';
  import { BasicTable, useTable } from '/@/components/Table';
  import { BasicDrawer, useDrawerInner, useDrawer } from '/@/components/Drawer';
  import { ListSelect } from '/@/components/ListSelect';
  import {
    PoOrder,
    poOrderSave,
    poOrderForm,
    poOrderCloseRow,
    poOrderOpenRow,
  } from '/@/api/m8/pu/order/poOrder';
  import GlobalSettingEnum from '/@/enums/globalSetting';
  import InputForm from './formSys.vue';
  import { basVenTreeData } from '/@/api/bas/ven/basVen';

  const emit = defineEmits(['success', 'register']);

  const { t } = useI18n('pu.order.poOrder');
  const { showMessage } = useMessage();
  const { meta } = unref(router.currentRoute);
  const record = ref<PoOrder>({} as PoOrder);
  // 图纸列表选择
  const selectListRef = ref<Recordable[]>([]);
  let queryParams = ref({});
  let orderPicSelectRef = ref<any>(null);
  let allowEdit = ref<boolean>();

  const getTitle = computed(() => ({
    icon: meta.icon || 'i-ant-design:book-outlined',
    value: record.value.isNewRecord ? t('新增采购订单') : t('编辑采购订单'),
  }));

  const inputFormSchemas: FormSchema[] = [
    {
      label: t('采购单号'),
      field: 'code',
      component: 'Input',
      componentProps: {
        maxlength: 64,
      },
      rules: [
        { required: false },
        { pattern: /^[a-zA-Z0-9_]*$/, message: t('请输入字母数字下划线') },
      ],
      colProps: { lg: 12, md: 12 },
      dynamicDisabled: true,
    },
    {
      label: t('单据日期'),
      field: 'ddate',
      component: 'DatePicker',
      componentProps: {
        format: 'YYYY-MM-DD',
        showTime: false,
        valueFormat: 'YYYY-MM-DD',
      },
      dynamicDisabled: true,
      required: true,
      colProps: { lg: 12, md: 12 },
    },
    {
      label: t('供应商'),
      field: 'venCode',
      fieldLabel: 'basVen.name',
      component: 'TreeSelect',
      componentProps: {
        api: basVenTreeData,
        allowClear: true,
      },
      required: true,
      colProps: { lg: 24, md: 24 },
    },
    {
      label: t('制单人'),
      field: 'createByName',
      component: 'Input',
      componentProps: {
        maxlength: 64,
      },
      colProps: { lg: 12, md: 12 },
      dynamicDisabled: true,
    },
    {
      label: t('修改人'),
      field: 'updateByName',
      component: 'Input',
      componentProps: {
        maxlength: 64,
      },
      colProps: { lg: 12, md: 12 },
      dynamicDisabled: true,
    },
    {
      label: t('备注信息'),
      field: 'remarks',
      component: 'InputTextArea',
      componentProps: {
        maxlength: 600,
      },
      colProps: { lg: 24, md: 24 },
    },
    {
      label: t('单据状态'),
      field: 'djStatus',
      component: 'Select',
      componentProps: {
        dictType: 'dj_status',
        allowClear: true,
      },
      ifShow: false,
    },
    {
      label: t('订单明细'),
      field: 'poOrderCList',
      component: 'Input',
      colProps: { lg: 24, md: 24 },
      slot: 'poOrderCList',
    },
  ];

  const [registerSysDrawer, { openDrawer }] = useDrawer();
  const [registerForm, { resetFields, setFieldsValue, updateSchema, validate }] = useForm({
    labelWidth: 120,
    schemas: inputFormSchemas,
    baseColProps: { lg: 8, md: 24 },
  });

  const [registerPoOrderCTable, poOrderCTable] = useTable({
    actionColumn: {
      width: 60,
      actions: (record: Recordable) => [
        {
          icon: 'i-ant-design:delete-outlined',
          color: 'error',
          popConfirm: {
            title: '是否确认删除',
            confirm: handlePoOrderCDelete.bind(this, record),
          },
          auth: 'pu:order:poOrder:edit',
          ifShow: () => allowEdit.value,
        },
      ],
    },
    rowKey: 'id',
    pagination: false,
    bordered: true,
    size: 'small',
    inset: true,
    rowSelection: {
      type: 'checkbox',
    },
  });

  async function setPoOrderCTableData(_res: Recordable) {
    poOrderCTable.setColumns([
      {
        title: t('销售订单ID'),
        dataIndex: 'soId',
        width: 130,
        align: 'left',
        editRow: true,
        editComponent: 'Input',
        editComponentProps: {
          maxlength: 64,
        },
        editRule: true,
        ifShow: false,
      },
      {
        title: t('图纸ID'),
        dataIndex: 'picId',
        width: 130,
        align: 'left',
        editRow: true,
        editComponent: 'Input',
        editComponentProps: {
          maxlength: 100,
        },
        editRule: true,
        ifShow: false,
      },
      {
        title: t('图名'),
        dataIndex: 'picName',
        width: 230,
        align: 'left',
        editRow: false,
        editComponent: 'Input',
        editComponentProps: {
          maxlength: 100,
        },
        editRule: true,
      },
      {
        title: t('客户'),
        dataIndex: 'cusCode',
        width: 230,
        align: 'left',
        editRow: true,
        editComponent: 'Input',
        editComponentProps: {
          maxlength: 64,
        },
        editRule: false,
        ifShow: false,
      },
      {
        title: t('数量'),
        dataIndex: 'iqty',
        width: 80,
        align: 'center',
        editRow: true,
        editComponent: 'InputNumber',
        editComponentProps: {
          maxlength: 16,
          min: 0,
        },
        editRule: true,
      },
      {
        title: t('单价'),
        dataIndex: 'fprice',
        width: 80,
        align: 'center',
        editRow: true,
        editComponent: 'InputNumber',
        editComponentProps: {
          maxlength: 16,
          min: 0,
        },
        editRule: false,
      },
      {
        title: t('金额'),
        dataIndex: 'fmoney',
        width: 80,
        align: 'center',
        editRow: true,
        editComponent: 'Input',
        editComponentProps: {
          maxlength: 16,
          disabled: true,
        },
        editRule: false,
      },
      {
        title: t('累计入库数'),
        dataIndex: 'inQty',
        width: 80,
        align: 'right',
        editRow: false,
        editComponent: 'Input',
        editComponentProps: {
          maxlength: 16,
        },
        editRule: false,
        ifShow: computed(() => !(!record.value.djStatus || record.value.djStatus == '9')),
      },
      {
        title: t('行状态'),
        dataIndex: 'rowStatus',
        width: 80,
        align: 'center',
        dictType: 'dj_row_status',
        editRow: false,
        editComponent: 'Select',
        editComponentProps: {
          dictType: 'dj_row_status',
          allowClear: true,
        },
        editRule: false,
        fixed: 'right',
      },
      {
        title: t('关闭日期'),
        dataIndex: 'closeDate',
        width: 130,
        align: 'center',
        editRow: false,
        editComponent: 'DatePicker',
        editComponentProps: {
          format: 'YYYY-MM-DD HH:mm',
          showTime: { format: 'HH:mm' },
        },
        editRule: false,
        ifShow: computed(() => !(!record.value.djStatus || record.value.djStatus == '9')),
      },
      {
        title: t('关闭人'),
        dataIndex: 'closeByName',
        width: 100,
        align: 'left',
        editRow: false,
        editComponent: 'Input',
        editComponentProps: {
          maxlength: 100,
        },
        editRule: false,
        ifShow: computed(() => !(!record.value.djStatus || record.value.djStatus == '9')),
      },
      {
        title: t('备注信息'),
        dataIndex: 'remarks',
        width: 130,
        align: 'left',
        editRow: true,
        editComponent: 'InputTextArea',
        editComponentProps: {
          maxlength: 500,
        },
        editRule: false,
      },
    ]);
    poOrderCTable.setTableData(record.value.poOrderCList || []);
  }

  function handlePoOrderCRowClick(record: Recordable) {
    record.onEdit?.(true, false);
  }

  function handlePoOrderCAdd() {
    // 打开图纸列表选择
    orderPicSelectRef.value.openSelectModal();
  }

  function handleFormSys() {
    openDrawer(true, {});
  }

  function handlePoOrderCDelete(record: Recordable) {
    poOrderCTable.deleteTableDataRecord(record);
  }

  async function getPoOrderCList() {
    let poOrderCListValid = true;
    let poOrderCList: Recordable[] = [];
    for (const record of poOrderCTable.getDataSource()) {
      if (!(await record.onEdit?.(false, true))) {
        poOrderCListValid = false;
      }
      poOrderCList.push({
        ...record,
        id: !!record.isNewRecord ? '' : record.id,
      });
    }
    for (const record of poOrderCTable.getDelDataSource()) {
      if (!!record.isNewRecord) continue;
      poOrderCList.push({
        ...record,
        status: '1',
      });
    }
    if (!poOrderCListValid) {
      throw { errorFields: [{ name: ['poOrderCList'] }] };
    }
    return poOrderCList;
  }

  const [registerDrawer, { setDrawerProps, closeDrawer }] = useDrawerInner(async (data) => {
    setDrawerProps({ loading: true });
    await resetFields();
    const res = await poOrderForm(data);
    record.value = (res.poOrder || {}) as PoOrder;
    record.value.__t = new Date().getTime();
    allowEdit.value = record.value.allowEdit;
    setDrawerProps({ showOkBtn: allowEdit.value });
    setFieldsValue(record.value);
    setPoOrderCTableData(res);
    updateSchema([
      {
        field: 'code',
        componentProps: {
          disabled: !record.value.isNewRecord,
        },
      },
    ]);
    setDrawerProps({ loading: false });
  });

  async function rowChange({ column, value, record: record1 }) {
    if (column.dataIndex === 'iqty') {
      console.log(record1);
      const {
        editValueRefs: { fprice, iqty, fmoney },
      } = record1;
      if (fprice.value && iqty.value) {
        fmoney.value = fprice.value * iqty.value;
      }
    }

    if (column.dataIndex === 'fprice' ) {
      const {
        editValueRefs: { fprice, iqty, fmoney },
      } = record1;
      if (fprice.value && iqty.value) {
        fmoney.value = fprice.value * iqty.value
      }
    }
}

  function handleSuccess(selectData) {
    selectData.forEach((item, index) => {
      let flag = true;
      poOrderCTable.getDataSource().forEach((res) => {
        if (res.picId == item.id) {
          flag = false;
        }
      });
      if (flag) {
        poOrderCTable.insertTableDataRecord({
          // ...item,
          // isNewRecord: true,
          // editable: true,
          id: new Date().getTime() + index,
          isNewRecord: true,
          editable: true,
          soId: item.order.id,
          picId: item.id,
          picName: item.picname,
          cusCode: item.order.cusCode,
          // fprice: item.fprice,
          // fmoney: Number(item.iqty).toFixed(2) * Number(item.fprice).toFixed(2),
          iqty: item.iqty,
          rowStatus: '0',
        });
      }
    });
  }

  // 图纸列表选择
  async function handleOrderPicSelect(values: Recordable[]) {
    console.log('选择内容', values);
    if (values.length == 0) {
      showMessage(t('请选择一条记录!'));
      return;
    }
    // 循环调用poOrderCTable.insertTableDataRecord 插入数据
    values.forEach((item, index) => {
      let flag = true;
      poOrderCTable.getDataSource().forEach((res) => {
        if (res.picId == item.id) {
          flag = false;
        }
      });
      if (flag) {
        poOrderCTable.insertTableDataRecord({
          id: new Date().getTime() + index,
          isNewRecord: true,
          editable: true,
          soId: item.order.id,
          picId: item.id,
          picName: item.picname,
          cusCode: item.order.cusCode,
          iqty: item.iqty,
          rowStatus: '0',
          // fprice: item.fprice,
          // fmoney: Number(item.iqty).toFixed(2) * Number(item.fprice).toFixed(2),
          //inQty: item.iqty,
        });
      }
    });
    selectListRef.value = []; // 清空选择的内容
  }

  async function handleCloseRow() {
    if (poOrderCTable.getSelectRowKeys().length) {
      const data = await poOrderCloseRow({ selIds: poOrderCTable.getSelectRowKeys().join(',') });
      showMessage(data.message);
      const res = await poOrderForm({ code: record.value.code });
      record.value = (res.poOrder || {}) as PoOrder;
      setFieldsValue(record.value);
      setPoOrderCTableData(res);
    } else {
      showMessage('请至少选择一行数据！！', 'warning');
    }
  }

  async function handleOpenRow() {
    if (poOrderCTable.getSelectRowKeys().length) {
      const data = await poOrderOpenRow({ selIds: poOrderCTable.getSelectRowKeys().join(',') });
      showMessage(data.message);
      const res = await poOrderForm({ code: record.value.code });
      record.value = (res.poOrder || {}) as PoOrder;
      setFieldsValue(record.value);
      setPoOrderCTableData(res);
    } else {
      showMessage('请至少选择一行数据！！', 'warning');
    }
  }

  async function handleSubmit(status) {
    try {
      const data = await validate();
      setDrawerProps({ confirmLoading: true });
      const params: any = {
        isNewRecord: record.value.isNewRecord,
        code: record.value.code,
      };
      data.poOrderCList = await getPoOrderCList();
      data.status = status;
      // console.log('submit', params, data, record);
      const res = await poOrderSave(params, data);
      showMessage(res.message);
      setTimeout(closeDrawer);
      if(status == '4'){
        emit('successPrint', res.data);
      }else{
        emit('success', data);
      }
      
    } catch (error: any) {
      if (error && error.errorFields) {
        showMessage(t('common.validateError'));
      }
      console.log('error', error);
    } finally {
      setDrawerProps({ confirmLoading: false });
    }
  }
</script>
